import { useEffect, useState } from 'react';
import { Select, Spin } from 'antd';
import type { SelectProps } from 'antd';
import { useBoolean } from 'ahooks';
import { getRoleList } from 'src/api/modules/system';
import { IRoleRespData } from 'src/interface';
import { debounce } from 'lodash-es';

export default function RoleSelect(props: SelectProps) {
  const [loading, { setTrue, setFalse }] = useBoolean(false);
  const [list, setList] = useState<IRoleRespData[]>([]);

  const getRoleDataList = debounce(async (value?: string) => {
    setTrue();
    try {
      const roles = await getRoleList({ current: 1, size: 100, roleName: value });
      setList(roles.records ?? []);
    } catch (err) {
      console.log(err);
    } finally {
      setFalse();
    }
  }, 300);

  useEffect(() => {
    getRoleDataList();
  }, []);

  return (
    <Select
      allowClear
      {...props}
      mode="multiple"
      filterOption={false}
      onSearch={getRoleDataList}
      notFoundContent={loading ? <Spin size="small" /> : null}
      placeholder="请选择用户角色"
      loading={loading}
      options={list.map((item) => ({ value: item.roleId, label: item.roleName }))}></Select>
  );
}
